/**
 * Created by zhangqi on 2015/6/24.
 */
define(function(require,exports,module){
    require("commonStaticDirectory/plugins/artDialog/ui-dialog.css"); //artDialog弹窗
    require("commonStaticDirectory/plugins/artDialog/dialog-plus"); //artDialog弹窗js
    require("commonStaticDirectory/plugins/chooseOrg/chooseOrg.css"); //自身的样式
    var Ajax = require("commonStaticDirectory/plugins/ajax");
    var _ = require("commonStaticDirectory/plugins/underscore.min"); //工具库

    var ChooseOrg = function(){
        this.init.apply(this,arguments);
    };
    ChooseOrg.prototype = {
        constructor: ChooseOrg,
        options:{
            sId:"base_chooseOrg"+(new Date()).getTime()
        },
        init:function(options){
            this.options = $.extend({},this.options,options);
            this.selectList = []; //选中集合
            this.getData();
        },
        initDialog:function(isShowList){
            var t = this;
            var d = dialog({
                title: "选择"+t.responseData.title,
                fixed: true,
                //skin: 'base_artdialog_gray',
                ok:function(){
                    //提交结果集
                    if(!t.selectList.length){
                        layer.msg("请先选择数据", {offset: 0,shift:6});
                        return false;
                    }
                    var mainIds= [];
                    var normalIds = [];
                    t.$element.find(".base_chooseOrg_selectbox").find(".selectItem").each(function(){
                        normalIds.push($(this).attr("data-key"));
                        if($(this).find(".selectItem_mainId").hasClass("checked")){
                            mainIds.push($(this).attr("data-key"));
                        }
                    });
                    var pageLayer = layer.load(1, {shade: [0.5,'#ccc']}); //启动遮罩
                    Ajax.ajax({
                        url:gMain.basePath + t.responseData.actionUrl,
                        data:JSON.stringify({
                            editConditionValue: t.options.editCondition.value,
                            mainIds: mainIds.join(","),
                            normalIds: normalIds.join(",")
                        }),
                        dataType:"json",
                        success:function(data){
                            if(data.result == "true"){
                                typeof t.options.callback == "function" && t.options.callback(); //保存成功的回调
                            }
                            layer.close(pageLayer);//关闭遮罩
                        }
                    });

                },
                cancel:function(){

                },
                content: '<div class="base_chooseOrg_dialog clearfix" style="'+(isShowList?'width:950px;':'width:465px;')+';">'+
                '    <div class="base_chooseOrg_row">'+
                '        <!--左树-->'+
                '        <div id="ztree-'+ t.options.sId+'" class="base_chooseOrg_dialog_tree ztree">'+
                '            树数据加载中...'+
                '        </div>'+
                '        <!--中间表格及搜索-->'+
                '        <div class="base_chooseOrg_dialog_tableandsearch" style="'+(isShowList?'':'display:none')+';">'+
                '            <!--搜索-->'+
                '            <div class="base_chooseOrg_search">'+
                '                <input type="text" class="base_chooseOrg_keyword"/>'+
                '                <input type="button" class="base_chooseOrg_searchtext iconfont_dayhr_base" value="&#xe601;"/>'+
                '            </div>'+
                '            <!--表格-->'+
                '            <div class="base_chooseOrg_table mmg-small">'+
                '                <table id="mmg-'+ t.options.sId+'" class="mmg">'+
                '                </table>'+
                '                <div class="mmGridTools">'+
                '                    <div id="mmpager-'+ t.options.sId+'"></div>'+
                '                </div>'+
                '            </div>' +
                '        </div>'+
                '        <!--右侧选择结果集-->' +
                '        <div class="base_chooseOrg_select_result">' +
                '            <input type="button" class="left_button flat-button flat-medium flat-blue" value="选择>>"/>'+
                '            <div class="base_chooseOrg_selectbox"></div>'+
                '        </div>'+
                '    </div>'+
                '</div>'
            });
            t.chooseDialog = d;
            t.chooseDialog.showModal();//模态弹出
            t.$element = $(".base_chooseOrg_dialog");
        },
        getData:function(){
            var t = this;
            Ajax.ApiTools().getChooseData({
                infoSetId: t.options.infoSetId,
                data:{infoSetId: t.options.infoSetId},
                success:function(data){
                    t.responseData = data;
                    t.initDialog(data.isShowList); //如果isShowList为true表示显示表格列表，否则不显示，就只是在tree上选择
                    t.initZtree(data.nodeList,data.isShowList);
                    if(data.isShowList){
                        t.initTable(data);
                    }
                    t.bindBtnEvent(data.isShowList);
                }
            });
        },
        //绑定按钮事件
        bindBtnEvent:function(isShowList){
            var t = this;
            //选择
            t.$element.find(".left_button").on("click",function(){
                var aSelectItem = [];
                if(isShowList){
                    var aSelect= t.mmg.selectedRows(); //表格选中的集合
                    var _key = t.responseData.submitId;
                    var _title = t.aListShowFields[0];
                    if(aSelect.length){
                        for(var i=0;i<aSelect.length;i++){
                            var item = aSelect[i];
                            aSelectItem.push({key:item[_key] +"",value:item[_title]});
                        }
                    }
                }else{
                    if(t.treeObj){
                        var aNodes = t.treeObj.getCheckedNodes(true); //true表示被勾选的集合
                        if(aNodes.length){
                            for(var i=0;i<aNodes.length;i++){
                                aSelectItem.push({key:aNodes[i].id,value:aNodes[i].name});
                            }
                        }
                    }
                }

                if(aSelectItem.length){
                    var aHtml = [];
                    for(var i=0;i<aSelectItem.length;i++){
                        //如果结果集中没有才添加
                        if(_.indexOf(t.selectList,aSelectItem[i].key) == -1){
                            t.selectList.push(aSelectItem[i].key);
                            aHtml.push('<div class="selectItem" data-key="'+aSelectItem[i].key+'"><span class="selectItem_value" title="'+aSelectItem[i].value+'">'+aSelectItem[i].value+'</span><span class="selectItem_operate"><a href="javascript:;" class="selectItem_mainId iconfont_dayhr_base" title="设为负责'+ t.responseData.title+'">&#xe608;</a><a href="javascript:;" class="selectItem_close" title="移除">x</a></span></div>');
                        }
                    }
                    $(this).parent().find(".base_chooseOrg_selectbox").append(aHtml.join(""));
                }
            });
            t.bindOperateItem(); //绑定操作选项的事件
        },
        //绑定移除选项的事件
        bindOperateItem:function(){
            var t = this;
            //移除
            t.$element.on("click",".selectItem_close",function(){
                var $parent = $(this).parent().parent();
                t.selectList = _.without(t.selectList,$parent.attr("data-key"));
                $parent.remove();
            });
            //操作
            t.$element.on("click",".selectItem_mainId",function(){
                if($(this).hasClass("checked")){$(this).removeClass("checked").attr("title","设为负责"+ t.responseData.title);}else{$(this).addClass("checked").attr("title","取消设为负责"+ t.responseData.title);}
            });
        },
        initZtree:function(data,isShowList){
            var t = this;
            if(!data || (data && !data.length)){
                $("#ztree-"+t.options.sId).text("暂无"+ t.responseData.title+"信息");
                return;
            }
            t.zTreeSetting = {
                view:{showIcon:false},
                callback:{}
            };
            //如果不显示表格，就是显示多选树
            if(!isShowList){
                t.zTreeSetting.check ={
                    enable: true,
                    chkStyle: "checkbox",
                    radioType: "all",
                    chkboxType: { "Y": "", "N": "" }
                };
            }else{
                //显示表格，就选中树，初始化表格
                t.zTreeSetting.callback.onClick=function(event, treeId, treeNode){
                    //根据节点数据重载表格
                    t.queryGetAllNode = treeNode;
                    t.mmg.load();
                }
            }
            for(var i=0;i<data.length;i++){
                data[i].open = true;
            }
            $.fn.zTree.init($("#ztree-"+t.options.sId), t.zTreeSetting, data);
            t.treeObj = $.fn.zTree.getZTreeObj("ztree-"+t.options.sId);
            //如果有表格，就默认选中第一个节点
            if(isShowList){
                var aNodes = t.treeObj.getNodes();
                t.queryGetAllNode = aNodes[0]; //默认查询第一个节点的数据
                t.treeObj.selectNode(aNodes[0]);
            }
        },
        initTable:function(data){
            var t = this;
            var aCols = []; //表头
            t.aListShowFields = []; // 表格中可见的字段集,将要取第0个可见字段作为title显示
            if(data.columnEdit.length){
                for(var i=0;i<data.columnEdit.length;i++){
                    var item = data.columnEdit[i];
                    if(item.isListShow){
                        t.aListShowFields.push(item.name);
                    }
                    var colObj = {title:item.title,name:item.name,align:item.align,width:item.width,isLogicPrimaryKey:item.isLogicPrimaryKey,hidden:!item.isListShow,renderer:function(val,item,rowIndex){
                        return val;
                    }};
                    aCols.push(colObj);
                }

                t.mmg = $('#mmg-'+t.options.sId).mmGrid({
                    width:"auto"
                    , height:"250px"
                    , cols: aCols
                    , checkCol:true
                    , multiSelect: true
                    , fullWidthRows: true
                    , url: gMain.basePath+"route/getAll.do"
                    , autoLoad: true
                    , plugins: [
                        //翻页控件
                        $('#mmpager-'+t.options.sId).mmPaginator({isShowLimitList:false,isShowPageGoto:true})
                    ]
                    , params: function(mmg){
                        //如果这里有验证，在验证失败时返回false则不执行AJAX查询。
                        return {infoSetId: "template_model",navigationCondition:{key: "model_id",value: t.responseData.templateCode},editCondition:{key: t.responseData.leftTreeConditionId,value:t.queryGetAllNode.id}};
                    }
                });

            }

        }

    };
    module.exports = ChooseOrg;
});
